<template>
  <div class="abs-calculator">
    <div class="container">
      <header>
        <h1>ABS齿圈计算器</h1>
        <p class="subtitle">基于轮胎升级数据的ABS齿圈参数计算工具</p>
      </header>

      <div class="main-content">
        <!-- 原车数据 -->
        <div class="section">
          <div class="section-title">
            <h2>原车数据</h2>
            <van-button type="danger" size="small" @click="showOriginalTirePicker = true" round icon="setting-o">
              选择预设
            </van-button>
          </div>

          <div class="form-group">
            <label for="originalTireModel">轮胎型号</label>
            <van-field v-model="originalData.tireModel" placeholder="例如: 205/55R16" input-align="right" />
          </div>

          <div class="form-group">
            <label for="originalTireWidth">轮胎宽度 (mm)</label>
            <van-field v-model="originalData.tireWidth" type="digit" @input="calculateTireDiameters"
              input-align="right" />
          </div>

          <div class="form-group">
            <label for="originalAspectRatio">胎壁厚度 (%)</label>
            <van-field v-model="originalData.aspectRatio" type="digit" @input="calculateTireDiameters"
              input-align="right" />
          </div>

          <div class="form-group">
            <label for="originalRimDiameter">轮毂直径 (英寸)</label>
            <van-field v-model="originalData.rimDiameter" type="digit" @input="calculateTireDiameters"
              input-align="right" />
          </div>

          <div class="form-group">
            <label for="originalTireDiameter">轮胎直径 (mm)</label>
            <van-field v-model="originalData.tireDiameter" readonly input-align="right" />
          </div>

          <div class="subsection">
            <h3>ABS齿圈数据</h3>

            <div class="form-group">
              <label for="originalRingDiameter">齿圈直径 (mm)</label>
              <van-field v-model="originalData.ringDiameter" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="originalToothCount">齿圈齿数</label>
              <van-field v-model="originalData.toothCount" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="originalToothEdgeWidth">齿边宽度 (mm)</label>
              <van-field v-model="originalData.toothEdgeWidth" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="originalToothGap">空齿间距 (mm)</label>
              <van-field v-model="originalData.toothGap" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="originalToothWidth">实齿宽度 (mm)</label>
              <van-field v-model="originalData.toothWidth" type="digit" input-align="right" />
            </div>
          </div>
        </div>

        <!-- 升级数据 -->
        <div class="section">
          <div class="section-title">
            <h2>升级数据</h2>
            <van-button type="danger" size="small" @click="showUpgradeTirePicker = true" round icon="setting-o">
              选择预设
            </van-button>
          </div>

          <div class="form-group">
            <label for="upgradeTireModel">轮胎型号</label>
            <van-field v-model="upgradeData.tireModel" placeholder="例如: 225/50R17" input-align="right" />
          </div>

          <div class="form-group">
            <label for="upgradeTireWidth">轮胎宽度 (mm)</label>
            <van-field v-model="upgradeData.tireWidth" type="digit" @input="calculateTireDiameters"
              input-align="right" />
          </div>

          <div class="form-group">
            <label for="upgradeAspectRatio">胎壁厚度 (%)</label>
            <van-field v-model="upgradeData.aspectRatio" type="digit" @input="calculateTireDiameters"
              input-align="right" />
          </div>

          <div class="form-group">
            <label for="upgradeRimDiameter">轮毂直径 (英寸)</label>
            <van-field v-model="upgradeData.rimDiameter" type="digit" @input="calculateTireDiameters"
              input-align="right" />
          </div>

          <div class="form-group">
            <label for="upgradeTireDiameter">轮胎直径 (mm)</label>
            <van-field v-model="upgradeData.tireDiameter" readonly input-align="right" />
          </div>

          <div class="subsection">
            <h3>ABS齿圈数据</h3>

            <div class="form-group">
              <label for="upgradeRingDiameter">齿圈直径 (mm)</label>
              <van-field v-model="upgradeData.ringDiameter" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="upgradeToothCount">齿圈齿数</label>
              <van-field v-model="upgradeData.toothCount" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="upgradeToothEdgeWidth">齿边宽度 (mm)</label>
              <van-field v-model="upgradeData.toothEdgeWidth" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="upgradeToothGap">空齿间距 (mm)</label>
              <van-field v-model="upgradeData.toothGap" type="digit" input-align="right" />
            </div>

            <div class="form-group">
              <label for="upgradeToothWidth">实齿宽度 (mm)</label>
              <van-field v-model="upgradeData.toothWidth" type="digit" input-align="right" />
            </div>
          </div>

          <van-button type="primary" block @click="calculateABSData" class="calculate-btn">
            计算ABS齿圈数据
          </van-button>
        </div>
      </div>

      <!-- 计算结果 -->
      <div class="results" v-if="showResults">
        <div class="section-title">
          <h2>计算结果</h2>
        </div>

        <van-cell-group :inset="true">
          <van-cell title="新旧轮胎速比" :value="results.speedRatio" />
          <van-cell title="原车每齿/轮胎旋转距离 (mm)" :value="results.originalToothDistance" />
          <van-cell title="升级每齿/轮胎旋转距离 (mm)" :value="results.upgradeToothDistance" />
        </van-cell-group>

        <div class="section-title">
          <h3>反向推算验证</h3>
        </div>

        <van-cell-group :inset="true">
          <van-cell title="原车轮胎周长 (mm)" :value="results.originalCircumference" />
          <van-cell title="原车齿数周长 (mm)" :value="results.originalToothCircumference" />
          <van-cell title="原车误差 (mm)" :value="results.originalError" />
          <van-cell title="升级轮胎周长 (mm)" :value="results.upgradeCircumference" />
          <van-cell title="升级齿数周长 (mm)" :value="results.upgradeToothCircumference" />
          <van-cell title="升级误差 (mm)" :value="results.upgradeError" />
          <van-cell title="齿数+1的误差 (mm)" :value="results.errorPlusOne" />
          <van-cell title="齿数-1的误差 (mm)" :value="results.errorMinusOne" />
        </van-cell-group>

        <div class="recommended">
          <van-cell-group :inset="true">
            <van-cell title="推荐齿数" :value="results.recommendedToothCount" />
            <van-cell title="推荐直径 (mm)" :value="results.recommendedRingDiameter" />
          </van-cell-group>
        </div>
      </div>

      <!-- 使用说明 -->
      <div class="instructions">
        <h3>使用说明</h3>
        <ul>
          <li>在<strong>原车数据</strong>部分输入车辆原始轮胎和ABS齿圈数据</li>
          <li>在<strong>升级数据</strong>部分输入您计划升级的轮胎数据</li>
          <li>点击"计算ABS齿圈数据"按钮进行计算</li>
          <li>计算结果区域将显示详细的参数和推荐值</li>
          <li>使用预设按钮可快速选择常见轮胎规格</li>
        </ul>
      </div>
    </div>

    <van-popup v-model:show="showOriginalTirePicker" round position="bottom" :style="{ maxHeight: '60%' }">
      <van-picker title="选择原车轮胎预设" :columns="tirePresetColumns" @confirm="(value) => selectPreset('original', value)"
        @cancel="showOriginalTirePicker = false" :show-toolbar="true" />
    </van-popup>

    <van-popup v-model:show="showUpgradeTirePicker" round position="bottom" :style="{ maxHeight: '60%' }">
      <van-picker title="选择升级轮胎预设" :columns="tirePresetColumns" @confirm="(value) => selectPreset('upgrade', value)"
        @cancel="showUpgradeTirePicker = false" :show-toolbar="true" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { showToast } from 'vant';


// 常量定义
const PI = Math.PI;
const INCH_TO_MM = 25.4;

// 轮胎预设
const tirePresets = [
  { model: '185/65R14', width: 185, ratio: 65, rim: 14 },
  { model: '195/65R15', width: 195, ratio: 65, rim: 15 },
  { model: '205/55R16', width: 205, ratio: 55, rim: 16 },
  { model: '215/55R17', width: 215, ratio: 55, rim: 17 },
  { model: '225/45R18', width: 225, ratio: 45, rim: 18 },
  { model: '235/40R19', width: 235, ratio: 40, rim: 19 },
  { model: '245/35R20', width: 245, ratio: 35, rim: 20 },
  { model: '255/35R20', width: 255, ratio: 35, rim: 20 },
];

// 为Picker组件准备数据格式
const tirePresetColumns = tirePresets.map(preset => ({
  text: preset.model,
  value: preset.model,
  data: preset,
}));

// 状态管理
const showOriginalTirePicker = ref(false);
const showUpgradeTirePicker = ref(false);
const showResults = ref(false);

// 原车数据
const originalData = reactive({
  tireModel: '',
  tireWidth: '205',
  aspectRatio: '55',
  rimDiameter: '16',
  tireDiameter: '',
  ringDiameter: '108.5',
  toothCount: '48',
  toothEdgeWidth: '3',
  toothGap: '3.3',
  toothWidth: '3.4',
});

// 升级数据
const upgradeData = reactive({
  tireModel: '',
  tireWidth: '225',
  aspectRatio: '50',
  rimDiameter: '17',
  tireDiameter: '',
  ringDiameter: '',
  toothCount: '',
  toothEdgeWidth: '',
  toothGap: '',
  toothWidth: '',
});

// 计算结果
const results = reactive({
  speedRatio: '-',
  originalToothDistance: '-',
  upgradeToothDistance: '-',
  originalCircumference: '-',
  originalToothCircumference: '-',
  originalError: '-',
  upgradeCircumference: '-',
  upgradeToothCircumference: '-',
  upgradeError: '-',
  errorPlusOne: '-',
  errorMinusOne: '-',
  recommendedToothCount: '-',
  recommendedRingDiameter: '-',
});

// 选择轮胎预设
function selectPreset(type, preset) {
  const targetData = type === 'original' ? originalData : upgradeData;
  let tirePreset = preset.selectedOptions[0].data;
  targetData.tireModel = tirePreset.text || tirePreset.model;
  targetData.tireWidth = tirePreset.width.toString();
  targetData.aspectRatio = tirePreset.ratio.toString();
  targetData.rimDiameter = tirePreset.rim.toString();

  calculateTireDiameters();

  if (type === 'original') {
    showOriginalTirePicker.value = false;
  } else {
    showUpgradeTirePicker.value = false;
  }
}

// 计算轮胎直径
function calculateTireDiameters() {
  // 原车数据计算
  const origWidth = parseFloat(originalData.tireWidth) || 0;
  const origRatio = parseFloat(originalData.aspectRatio) || 0;
  const origRim = parseFloat(originalData.rimDiameter) || 0;

  // 升级数据计算
  const upgradeWidth = parseFloat(upgradeData.tireWidth) || 0;
  const upgradeRatio = parseFloat(upgradeData.aspectRatio) || 0;
  const upgradeRim = parseFloat(upgradeData.rimDiameter) || 0;

  // 计算轮胎直径
  const origDiameter = (origWidth * (origRatio / 100) * 2) + (origRim * INCH_TO_MM);
  const upgradeDiameter = (upgradeWidth * (upgradeRatio / 100) * 2) + (upgradeRim * INCH_TO_MM);

  // 更新显示
  originalData.tireDiameter = origDiameter.toFixed(2);
  upgradeData.tireDiameter = upgradeDiameter.toFixed(2);

  // 设置ABS齿圈升级数据默认值
  if (!upgradeData.toothEdgeWidth) {
    upgradeData.toothEdgeWidth = originalData.toothEdgeWidth;
  }

  if (!upgradeData.toothGap) {
    upgradeData.toothGap = originalData.toothGap;
  }

  if (!upgradeData.toothWidth) {
    upgradeData.toothWidth = originalData.toothWidth;
  }
}

// 计算ABS齿圈数据（优化后的算法）
function calculateABSData() {
  // 验证输入
  if (!validateInputs()) {
    return;
  }

  // 获取原车数据
  const origDiameter = parseFloat(originalData.tireDiameter);
  const origRingDiameter = parseFloat(originalData.ringDiameter);
  const origToothCount = parseFloat(originalData.toothCount);
  const origToothEdgeWidth = parseFloat(originalData.toothEdgeWidth);

  // 获取升级数据
  const upgradeDiameter = parseFloat(upgradeData.tireDiameter);
  const upgradeToothEdgeWidth = parseFloat(upgradeData.toothEdgeWidth) || origToothEdgeWidth;

  // 计算速比
  const speedRatio = upgradeDiameter / origDiameter;

  // 计算每齿距离
  const origCircumference = origDiameter * PI;
  const origToothDistance = origCircumference / origToothCount;

  const upgradeCircumference = upgradeDiameter * PI;
  const upgradeToothCount = origToothCount * speedRatio;

  // 计算升级齿圈数据（优化算法，考虑齿圈实际尺寸）
  const effectiveOrigRingDiameter = origRingDiameter - 2 * origToothEdgeWidth;
  const upgradeRingDiameter = effectiveOrigRingDiameter * speedRatio + 2 * upgradeToothEdgeWidth;

  // 计算误差
  const upgradeToothDistance = upgradeCircumference / (origToothCount * speedRatio);
  const upgradeToothCircumference = upgradeToothCount * origToothDistance;
  const upgradeError = upgradeCircumference - upgradeToothCircumference;

  // 计算齿数±1的误差
  const errorPlusOne = upgradeCircumference - ((upgradeToothCount + 1) * origToothDistance);
  const errorMinusOne = upgradeCircumference - ((upgradeToothCount - 1) * origToothDistance);

  // 智能推荐齿数（考虑整数齿数并选择误差最小的）
  const intToothCount = Math.round(upgradeToothCount);
  const errors = [
    { count: intToothCount, error: Math.abs(upgradeCircumference - (intToothCount * origToothDistance)) },
    { count: intToothCount + 1, error: Math.abs(errorPlusOne) },
    { count: intToothCount - 1, error: Math.abs(errorMinusOne) }
  ];

  errors.sort((a, b) => a.error - b.error);
  const recommendedToothCount = errors[0].count;

  // 计算推荐直径（基于推荐齿数）
  const recommendedRingDiameter = effectiveOrigRingDiameter *
    (recommendedToothCount / origToothCount) +
    2 * upgradeToothEdgeWidth;

  // 更新数据
  upgradeData.ringDiameter = upgradeRingDiameter.toFixed(2);
  upgradeData.toothCount = upgradeToothCount.toFixed(2);

  // 更新结果
  results.speedRatio = speedRatio.toFixed(4);
  results.originalToothDistance = origToothDistance.toFixed(2);
  results.upgradeToothDistance = upgradeToothDistance.toFixed(2);
  results.originalCircumference = origCircumference.toFixed(2);
  results.originalToothCircumference = (origToothCount * origToothDistance).toFixed(2);
  results.originalError = (origCircumference - origToothCount * origToothDistance).toFixed(2);
  results.upgradeCircumference = upgradeCircumference.toFixed(2);
  results.upgradeToothCircumference = upgradeToothCircumference.toFixed(2);
  results.upgradeError = upgradeError.toFixed(2);
  results.errorPlusOne = errorPlusOne.toFixed(2);
  results.errorMinusOne = errorMinusOne.toFixed(2);
  results.recommendedToothCount = recommendedToothCount;
  results.recommendedRingDiameter = recommendedRingDiameter.toFixed(2);

  showResults.value = true;
}

// 验证输入数据
function validateInputs() {
  const requiredFields = [
    { name: '原车轮胎宽度', value: originalData.tireWidth },
    { name: '原车胎壁厚度', value: originalData.aspectRatio },
    { name: '原车轮毂直径', value: originalData.rimDiameter },
    { name: '原车齿圈直径', value: originalData.ringDiameter },
    { name: '原车齿圈齿数', value: originalData.toothCount },
    { name: '升级轮胎宽度', value: upgradeData.tireWidth },
    { name: '升级胎壁厚度', value: upgradeData.aspectRatio },
    { name: '升级轮毂直径', value: upgradeData.rimDiameter }
  ];

  for (const field of requiredFields) {
    if (!field.value || isNaN(parseFloat(field.value))) {
      showToast(`请输入有效的${field.name}`);
      return false;
    }
  }

  return true;
}

// 组件加载时计算轮胎直径
onMounted(() => {
  calculateTireDiameters();
});
</script>

<style scoped>
.abs-calculator {
  background-color: var(--bg-dark);
  color: var(--text-color);
  padding-bottom: 20px;
  height: 100%;
  overflow: auto;
  position: relative;
}

.container {
  max-width: 100%;
  margin: 0 auto;
}

header {
  background: linear-gradient(135deg, #ff3a3a, #ff7676);
  color: white;
  padding: 15px 10px 10px 10px;
  box-sizing: border-box;
  text-align: center;
  box-shadow: 0 2px 10px rgba(255, 58, 58, 0.3);
}

h1 {
  font-size: 1.6rem;
  margin-bottom: 8px;
  font-weight: bold;
}

.subtitle {
  font-size: 0.9rem;
  opacity: 0.9;
}

.main-content {
  padding: 12px;
}

.section {
  background-color: var(--bg-darker);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 58, 58, 0.2);
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 58, 58, 0.2);
}

h2 {
  font-size: 1.2rem;
  color: var(--primary-color);
  margin: 0;
  font-weight: bold;
}

h3 {
  font-size: 1rem;
  color: var(--primary-color);
  margin: 12px 0 8px;
  font-weight: bold;
}

.subsection {
  background-color: rgba(15, 25, 35, 0.3);
  padding: 12px;
  border-radius: 10px;
  margin-top: 12px;
}

.form-group {
  margin-bottom: 8px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

label {
  font-weight: 500;
  font-size: 0.9rem;
  color: var(--text-secondary);
  flex: 0 0 40%;
}

.form-group .van-field {
  flex: 0 0 58%;
  padding: 0;
}

:deep(.van-field__control) {
  height: 36px;
  line-height: 36px;
  padding: 0 8px;
  background-color: rgba(30, 40, 50, 0.6);
  border-radius: 6px;
  color: var(--text-color);
  font-weight: 500;
}

.calculate-btn {
  margin-top: 20px;
  height: 44px;
  background: linear-gradient(135deg, #ff3a3a, #ff7676);
  border: none;
  position: relative;
  overflow: hidden;
  border-radius: 22px;
  font-weight: bold;
  font-size: 1.1rem;
  box-shadow: 0 4px 12px rgba(255, 58, 58, 0.3);
}

.calculate-btn::after {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: 0.5s;
}

.calculate-btn:active {
  transform: scale(0.98);
}

.calculate-btn:hover::after {
  left: 100%;
}

.results {
  background-color: var(--bg-darker);
  border-radius: 12px;
  padding: 16px;
  margin: 0 12px 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 58, 58, 0.2);
}

.recommended {
  margin-top: 16px;
  padding: 12px;
  border-radius: 10px;
  background-color: rgba(255, 58, 58, 0.1);
}

.instructions {
  background-color: rgba(15, 25, 35, 0.7);
  padding: 16px;
  border-radius: 12px;
  margin: 0 12px;
  font-size: 0.9rem;
  border: 1px solid rgba(255, 58, 58, 0.2);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.instructions h3 {
  margin-top: 0;
  margin-bottom: 10px;
}

.instructions ul {
  padding-left: 20px;
  margin: 0;
}

.instructions li {
  margin-bottom: 8px;
  line-height: 1.4;
}

:deep(.van-cell) {
  background-color: transparent;
  padding: 10px 12px;
}

:deep(.van-cell-group--inset) {
  margin: 0;
  border-radius: 8px;
  overflow: hidden;
  background-color: rgba(15, 25, 35, 0.3);
}

:deep(.van-popup) {
  background-color: var(--bg-dark);
}

:deep(.van-picker) {
  background-color: #cac9c9;
  color: #000;
  height: auto;
}

:deep(.van-picker__toolbar) {
  background-color: #f1050565;
  border-bottom: 1px solid rgba(255, 58, 58, 0.2);
  position: sticky;
  top: 0;
  z-index: 2;
}

:deep(.van-picker-column__item) {
  color: #333;
}

:deep(.van-picker-column__item--selected) {
  color: #000;
  font-weight: bold;
}

:deep(.van-field__body) {
  min-height: 36px;
}

:deep(.van-picker__title) {
  color: #fff;
}

:deep(.van-picker__confirm) {
  color: #fff;
}

:deep(.van-picker__cancel) {
  color: #fff;
}

:deep(.van-picker-column) {
  height: auto;
}

:deep(.van-picker-column__wrapper) {
  height: auto;
}

:deep(.van-field__control) {
  min-height: 36px;
}

:deep(.van-cell__title) {
  color: #fff;
}
</style>